<?php

namespace app\controller\v1;

use app\BaseController;
use think\App;
use think\facade\Db;
use think\facade\Request;

class System extends BaseController
{
    public $params = [];

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->params = input('post.');
        $this->params['login_user_id'] = $this->getUserInfo()['id'] ?? 0;
        $this->params['company_id'] = $this->getUserInfo()['company_id'] ?? 0;
    }


    public function getUserInfo()
    {
        $token = Request::header('Authorization');
        if (empty($token)) {
            return [];
        }

        // 去掉 Bearer 前缀
        $token = str_replace('Bearer ', '', $token);

        // 从tokens表查询token信息
        $tokenInfo = Db::name('user_tokens')
            ->where('token', $token)
            ->where('status', 1)
            ->find();

        $user = false;
        if (!empty($tokenInfo)) {
            // 根据user_id查询用户基本信息
            $user = Db::name('user')
                ->where('id', $tokenInfo['user_id'])
                ->where('status', 1)
                ->find();
            return $user;
        }

        return $user;

    }


    /**
     * Notes: 返回json 成功的方法
     * User: chenLei
     * Date: 9/7/25
     * @param $msg
     * @param $data
     * @param $code
     * @return \think\response\Json
     */
    public function successJson($msg = 'success', $data = [], $code = 200)
    {
        if (is_array($msg) || is_object($msg)) {
            $data = $msg;
            $msg = 'success';
        }
        return json([
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ]);
    }

    /**
     * Notes: 返回json 异常抛出
     * User: chenLei
     * Date: 9/7/25
     * @param $msg
     * @param $data
     * @param $code
     * @return \think\response\Json
     */
    public function errorJson($msg, $data = [], $code = 400)
    {
        return json([
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ]);
    }
}